<template>
    <div>
        <!--<div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 资料共享
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>-->
        <div>
			<el-tabs v-model="activeName" @tab-click="handleClick">
		    <el-tab-pane label="用户管理" name="first">资料列表</el-tab-pane>
		    <el-tab-pane label="目录展示" name="second">目录展示</el-tab-pane>
		  	</el-tabs>
  		</div>
        <div class="container" v-if="isShow_first">
            <div class="handle-box">
                <el-button type="success" @click="addEdit">上传文件</el-button>
                <el-button type="primary" @click="handleFolder('add')">新增文件夹</el-button>
		        <el-button type="info" :disabled="disabledEditFolder" class="handle-del mr10" @click="handleFolder('edit')">编辑文件夹</el-button>
		        <!--<el-button
                    type="danger"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >删除</el-button>-->
                <el-input v-model="query.fileName" placeholder="文件名" class="handle-input mr10"></el-input>
                <el-input v-model="query.realName" placeholder="上传者姓名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="" icon="el-icon-brush" @click="clearSearch">清空</el-button>
            </div>
            
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="fileId" label="文件ID" v-if="show"></el-table-column>
                <el-table-column prop="userId" label="上传者学号" v-if="show"></el-table-column>
                <el-table-column prop="fileName" label="文件资料"></el-table-column>
                <el-table-column prop="realName" label="上传者"></el-table-column>
                <el-table-column prop="orgName" label="所属部门"></el-table-column>
                <el-table-column prop="createTime" label="上传时间"></el-table-column>
                <el-table-column prop="updateTime" label="更新时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <!--<el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>-->
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

		<div class="container" v-if="isShow_second">
			
			<el-tree :data="treeDate" :props="defaultProps" default-expand-all @node-click="handleNodeClick"></el-tree>
		</div>
        <!-- 编辑弹出框 -->
        <el-dialog title="上传文件" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
            	<el-form-item label="新建目录" v-if = "this.editFoldevisible == true">
                    <el-input v-model="form.node_name"></el-input>
                </el-form-item>
                <el-form-item label="目录路径">
                   <select-tree v-model="selected" v-on:listenToChildEvent = 'showMsgfromChild' :options="options" :props="defaultProps2" @node-click="handleNode2Click" />
                </el-form-item>
                <el-form-item label="导入文件" v-if = "this.upfilevisible == true">
                    <el-upload 
	                	action=""
	                	class="upload-demo"
	                	drag
	                	:limit="3"
		            	:http-request="uploadMaterial">
		            <i class="el-icon-upload"></i>
		   			<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
		   			<div slot="tip" class="el-upload__tip">只能上传单个文件，多个文件请打包上传tar/zip，且不超过100MB</div>
		 			</el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="exit">退出</el-button>
                <el-button type="primary" v-if = "this.editFoldevisible == true" @click="addFolderHandle">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import SelectTree from './SelectTree.vue';
import axios from 'axios';
axios.defaults.timeout =  6000;
export default {
    name: 'basetable',
    components: {
	    SelectTree
	},
    data() {
        return {
            query: {
                fileName:'',
                realName:'',
                pageIndex: 1,
                pageSize: 10
            },
            show:false,
            tableData: [],
            treeDate:[],  //获取目录树和文件
            treeMenu:[],  //获取目录树
            defaultProps: {
            	parent: 'parentId',   // 父级唯一标识
            	value: 'treeId',          // 唯一标识
		        label: 'treename',       // 标签显示
		        children: 'children', // 子级
	        },
	        defaultProps2: {
	            parent: 'pid',   // 父级唯一标识
		        value: 'id',          // 唯一标识
		        label: 'name',       // 标签显示
		        children: 'childList', // 子级
	        },
	        layout: {
		        show_list: true, // 文件展示形式
		        edit_path: false, // 是否编辑路径
		        view: false, // 预览视图
		        move: false, // 移动视图
		        upload: false // 上传视图
		    }, // 视图管理
      		selected: -1, // 默认选中值
		    // 数据列表
	      	options: [/*{
	      		parentId: '0',
	      		id: 'A',
	      		label: 'label-A',
	      		children: [{
	      			parentId: 'A',
	      			id: 'A-1',
	      			label: 'label-A-1',
	      		}, ],
	      	}, {
	      		parentId: '0',
	      		value: 'B',
	      		label: 'label-B',
	      		children: [],
	      	}, */],
	      	multipleSelection: [],
	      	delList: [],
	      	editVisible: false,
	      	editFoldevisible:false,
	        upfilevisible:false,
	      	pageTotal: 0,
	      	activeName:'first',
            isShow_first:true,//标签页1设置默认显示
            isShow_second:false,//标签页2设置默认隐藏
            file_checked_data:[], // 列表多选数据
            downloadPath:'E:/work/down/3333/',
            form: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
        //this.getDataTree();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        async getData(){
	        let res = await this.$Http.getfileinfoList(
	        	{
	        		pageNum:this.query.pageIndex,
	        	},
                true
	        );
	        this.tableData = res.data.list;
	        this.pageTotal = res.data.total || 10;
	        
	    },
	    async getDataTree(){
	    	let res_tree = await this.$Http.getDataTree(
	        	{
	        		//pageNum:this.query.pageIndex,
	        	},
                true
	       );
	        console.log("tree:",res_tree);
	        this.treeDate = res_tree.data;
	    },
	    async getMenuTree(){
	    	let res_tree = await this.$Http.getMenuTree(
	        	{
	        		//pageNum:this.query.pageIndex,
	        	},
                true
	       );
	        console.log("Menu:",res_tree.data.list);
	        this.options = res_tree.data.list;
	    },
	    //选择文件下载
	    handleNodeClick(data) {
	        console.log(data);
	        if(data.dataTreeType=='FILE'){
	    		this.$confirm('是否要下载当前文件？', '提示', {
            })
	    		.then(() => {
	    			this.downloadMaterials(data)
                    
                })
                .catch(() => {});
            
	    	}
	    },
	    handleNode2Click(data){
	    	//console.log(this.selected);
	    },
        handleClick(tab, event) {
        	if (tab.name=='first'){
        		this.isShow_first=true
        		this.isShow_second=false
        		this.getData();
        	}else{
        		this.isShow_first=false
        		this.isShow_second=true
        		this.getDataTree();
        	}
        	console.log(tab, event);
      	},
      	exit(){
      		this.editVisible = false;
      		this.selected = -1;
      	},
      	//辅导员上传模板
      	showMsgfromChild(data){
      		console.log("监听子模块:"+data);
      		this.selected = Number(data);
      	},
	    //上传文件资料
		uploadMaterial(param) {
	    	let form = new FormData();
	    	var that = this;
	    	console.log(that.selected);
	    	if (that.selected < 0){
	    		 this.$message.error('请选择上传路径');
	    		 return;
	    	}
	    	form.append('file', param.file);
	    	form.append('node_id', that.selected);
	    	//form.append('fileName', param.fileName);
	    	//form.append('filePath', param.filePath);
	    	that.$axios.post('/file/uploadMaterials.do', form, {
	    		headers: {
	    			'Content-Type': 'multipart/form-data'
	    		},
	    		onUploadProgress: progressEvent => {
	    			that.uploadPercent = (progressEvent.loaded / progressEvent.total * 100) | 0;
	    		}
	    	}).then((res) => {
	    		console.log('上传结束');
	    		console.log(res.data);
	    		if (res.status == 0){
		        	this.selected = -1;
		        	this.form = []
		        }
	            this.$message.success(res.data.msg);
	    		
	    	}).catch((err) => {
	    		console.log('上传错误')
	    		console.log(err)
	    	})
	    },
	    async downloadMaterials(data){
	    	let res = await this.$Http.downloadMaterials(
	        	{
	        		fileName : data.treename,
	        		filePath : data.filePath,
	        		nodeId   : data.treeId,
	        		downloadPath : this.downloadPath
	        	},
                true
	       );
	        console.log("downlaodres:",res.msg);
	        this.$message.success(res.msg);
	    },
        /**
	     * 文件夹编辑操作
	     * type: string 添加add 编辑edit
	     * auth: boolean 是否只修改权限
	     */
	    handleFolder(type) {
	      this.title = "目录操作";
	      this.editVisible = true;
	      this.editFoldevisible = true;
	      this.upfilevisible = false;
	      this.getMenuTree()
	    },
	    
	    //新增文件夹
	    async addFolderHandle(){
	    	var that = this;
	    	console.log(that.selected);
	    	if (that.selected < 0){
	    		 this.$message.error('请选择上传路径');
	    		 return;
	    	}
	    	let res = await that.$Http.addFolderinfo(
	        	{
	        		parentId:that.selected,
	        		node_name:that.form.node_name
	        	},
                true
	       );
	        console.log("addFolderHandleRes:",res.data);
	        if (res.status == 0){
	        	this.selected = -1;
	        	this.form = []
	        }
            this.$message.success(res.msg);
	    },
//      // 显示上传界面
	    showUpload() {
	      if (this.useUpload) {
	        this.layout.upload = true;
	        this.$emit("closeFade");
	      } else {
	        this.$emit("showUpload");
	      }
	    },
	    // 关闭上传界面
	    closeUpload() {
	      this.layout.upload = false;
	    },
	    // 文件上传提交操作
	    saveUpload() {
	      this.$emit("upload", this.file, this.handleUpload);
	    },
	    // 手动上传文件
	    handleUpload() {
	      this.$refs["upload-item"].toUpload();
	    },
        // 触发搜索按钮
        async handleSearch() {
	        let res = await this.$Http.getFileinfoListByParams(
	        	{
	        		pageNum:this.query.pageIndex,
	        		fileName : this.query.fileName,
	        		realName : this.query.realName
	        	},
                true
	        );
	        //console.log(res.data);
	        //console.log(res.data.total);
	        this.tableData = res.data.list;
	        this.pageTotal = res.data.total || 10;

        },
        //清空搜索栏
        clearSearch(){
        	this.query.fileName=''
	        this.query.realName=''
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                	let res = this.deleteFileinfo(row);
                })
                .catch((err) => {this.$message.error(err);});
        },
        //删除
        async deleteFileinfo(row){
        	let res = await this.$Http.delFileinfo(
		    	{
		    		id : row.fileId,
		    		userId : row.userId
		    		
		    	},
		        true
		    );
		    console.log(res);
		    if (res.status == 0){
		    	this.$message.success(res.msg);
		    	this.delList = [];
		    }
		    this.$message.error(res.msg);
		    return res
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        // 新增操作
        addEdit(){
            this.editVisible = true;
            this.editFoldevisible = false,
	      	this.upfilevisible = true
            this.getMenuTree()
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`新增成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    },
    computed: {
    	// 是否禁用编辑文件夹按钮
	    disabledEditFolder() {
	      /*return (
	        this.file_checked_data.length !== 1 ||
	        !this.file_checked_data[0][this.selfIsFolder]
	      );*/
	    }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 200px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
